package com.ruoyi.procured.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.api.localInventory.dto.LocalInventoryDto;
import com.ruoyi.common.api.ordersProduct.OrdersProductApi;
import com.ruoyi.common.api.ordersProduct.dto.OrdersProductDTO;
import com.ruoyi.common.api.procured.ProcuredApi;
import com.ruoyi.common.api.procured.dto.ProcuredPlanDto;
import com.ruoyi.common.api.procuredOrders.ProcuredOrdersStatusAPi;
import com.ruoyi.common.api.procuredProduct.ProcuredProductApi;
import com.ruoyi.common.api.procuredProduct.dto.ProcuredProductDto;
import com.ruoyi.common.api.procuredStorage.dto.ProcuredStorageDto;
import com.ruoyi.common.api.sale.plan.SalePlanApi;
import com.ruoyi.common.api.walmartStockPlan.WalmartStockPlanApi;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.OrdersProduct;
import com.ruoyi.common.core.domain.ProcuredOrders;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.procured.domain.PaymentRequest;
import com.ruoyi.procured.domain.PaymentRequestLog;
import com.ruoyi.procured.domain.PaymentRequestProcess;
import com.ruoyi.procured.domain.PaymentReturn;
import com.ruoyi.procured.domain.vo.PaymentRequestProcessVo;
import com.ruoyi.procured.mapper.PaymentRequestLogMapper;
import com.ruoyi.procured.mapper.PaymentRequestMapper;
import com.ruoyi.procured.mapper.PaymentRequestProcessMapper;
import com.ruoyi.procured.mapper.PaymentReturnMapper;
import com.ruoyi.procured.service.IPaymentRequestProcessService;
import com.ruoyi.procured.service.IPaymentRequestService;
import com.ruoyi.procured.service.IPaymentReturnService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.template.domain.TemplateDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 申请付款Service业务层处理
 * 
 * @author 刘广帆
 * @date 2024-10-18
 */
@Service
public class PaymentRequestProcessServiceImpl implements IPaymentRequestProcessService
{

    @Autowired
    private PaymentRequestProcessMapper paymentRequestProcessMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PaymentRequestLogMapper paymentRequestLogMapper;
    @Autowired
    private PaymentRequestMapper paymentRequestMapper;
    @Autowired
    private PaymentReturnMapper paymentReturnMapper;
    @Autowired
    private IPaymentRequestService paymentRequestService;
    @Autowired
    private IPaymentReturnService paymentReturnService;
    @Autowired
    private WalmartStockPlanApi walmartStockPlanApi;
    @Autowired
    private ProcuredOrdersStatusAPi procuredOrdersStatusAPi;
    @Autowired
    private ProcuredProductApi procuredProductApi;
    @Autowired
    private OrdersProductApi ordersProductApi;
    @Autowired
    private ProcuredApi procuredApi;
    @Autowired
    private SalePlanApi salePlanApi;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 新增审核流程
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public void insertPaymentRequestProcessQuash(String paymentRequestId, List<TemplateDetail> templateDetails, Long userId) {

        for(TemplateDetail td : templateDetails){

            String UUID = IdUtils.fastSimpleUUID();
            String processStatus = Constants.PAYMENT_REQUEST_PROCESS_STATUS_PENDING;
            Date processTime = DateUtils.getNowDate();

            Long reviewerId = Long.valueOf(td.getReviewerId());
            SysUser user = sysUserMapper.selectUserById(reviewerId);
            Long reviewerDeptId = user.getDeptId();

            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserRole::getUserId, reviewerId);
            SysUserRole sur = sysUserRoleMapper.selectOne(queryWrapper);
            if(null == sur){
                throw new ServiceException(user.getNickName()+"未设置角色，请联系人事匹配后再操作。");
            }
            Long reviewerRoleId = sur.getRoleId();

            Integer reviewerOrder = td.getReviewOrder();

            PaymentRequestProcess pp = new PaymentRequestProcess(UUID,processStatus,null,paymentRequestId,reviewerId,reviewerDeptId,reviewerRoleId,reviewerOrder);
            paymentRequestProcessMapper.insert(pp);
        }

        //插入审核流程表日志
        SysUser user =  sysUserMapper.selectUserById(userId);
        savePaymentRequestLog(paymentRequestId,Constants.SUCCESS,user.getNickName(),"");
        /*
        //说明没有上级审核
        if(sysUserRoles.size()<=0){
            String UUID = IdUtils.fastSimpleUUID();
            String processStatus = Constants.PAYMENT_REQUEST_PROCESS_STATUS_PENDING;
            Date processTime = DateUtils.getNowDate();
            Long reviewerId = userId;

            SysUser user = sysUserMapper.selectUserById(userId);
            Long reviewerDeptId = user.getDeptId();

            LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUserRole::getUserId, userId);
            SysUserRole sur = sysUserRoleMapper.selectOne(queryWrapper);
            Long reviewerRoleId = sur.getRoleId();

            PaymentRequestProcess pp = new PaymentRequestProcess(UUID,processStatus,null,paymentRequestId,reviewerId,reviewerDeptId,reviewerRoleId);
            paymentRequestProcessMapper.insert(pp);
        }else{
            for(SysUserRole role : sysUserRoles){
                String UUID = IdUtils.fastSimpleUUID();
                String processStatus = Constants.PAYMENT_REQUEST_PROCESS_STATUS_PENDING;
                Date processTime = DateUtils.getNowDate();
                Long reviewerId = role.getUserId();

                SysUser user = sysUserMapper.selectUserById(reviewerId);
                Long reviewerDeptId = user.getDeptId();

                Long reviewerRoleId = role.getRoleId();

                PaymentRequestProcess pp = new PaymentRequestProcess(UUID,processStatus,null,paymentRequestId,reviewerId,reviewerDeptId,reviewerRoleId);
                paymentRequestProcessMapper.insert(pp);
            }
        }
        */
    }

    /**
     * 查询审核流程
     * @param paymentRequestId
     * @return
     */
    @Override
    public List<PaymentRequestProcessVo> selectPaymentRequestProcessList(String paymentRequestId) {

        return paymentRequestProcessMapper.selectPaymentRequestProcessList(paymentRequestId);
    }
    /**
     * 更新审核流程状态
     * @param paymentRequestProcess
     * @return
     */
    @Override
    @Transactional
    public int updateProcessStatus(PaymentRequestProcess paymentRequestProcess) {

        Long reviewerId = paymentRequestProcess.getReviewerId();
        String paymentRequestId = paymentRequestProcess.getPaymentRequestId();
        String processStatus = paymentRequestProcess.getProcessStatus();
        String processRemark = paymentRequestProcess.getProcessRemark();

        //更新审核流程表
        LambdaUpdateWrapper<PaymentRequestProcess> updateWrapper  = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PaymentRequestProcess::getPaymentRequestId,paymentRequestId);
        updateWrapper.eq(PaymentRequestProcess::getReviewerId,reviewerId);
        updateWrapper.set(PaymentRequestProcess::getProcessStatus, processStatus);
        updateWrapper.set(PaymentRequestProcess::getProcessTime,DateUtils.getNowDate());
        updateWrapper.set(PaymentRequestProcess::getProcessRemark,processRemark);
        paymentRequestProcessMapper.update(null,updateWrapper);

        //插入审核流程表日志
        SysUser user =  sysUserMapper.selectUserById(reviewerId);
        savePaymentRequestLog(paymentRequestId,processStatus,user.getNickName(),processRemark);


        //汇总状态，更新到申请付款表
        List<String> statuses = paymentRequestProcessMapper.selectStatusesByPaymentRequestId(paymentRequestId);
        String newStatus;
        if (statuses.contains("2")) {
            newStatus =  Constants.PAYMENT_REVIEW_STATUS_REJECTED; // 有任何一条为 "2"，则设为驳回状态
        } else if (statuses.stream().allMatch(status -> "1".equals(status))) {
            newStatus = Constants.PAYMENT_REVIEW_STATUS_APPROVED; // 如果所有记录都为 "1"，则设为已审核
        } else {
            newStatus = Constants.PAYMENT_REVIEW_STATUS_PENDING; // 0 否则为审核中
        }
        Long reviewerUserId = paymentRequestMapper.selectById(paymentRequestId).getReviewerUserId();

        if(processStatus.equals("1")){

            LambdaQueryWrapper<PaymentRequestProcess> qw = new LambdaQueryWrapper<>();
            qw.eq(PaymentRequestProcess::getPaymentRequestId,paymentRequestId);
            qw.eq(PaymentRequestProcess::getReviewerId,reviewerId);
            PaymentRequestProcess pp = paymentRequestProcessMapper.selectOne(qw);
            if(pp == null){
                throw new ServiceException("获取审核流程明细失败。");
            }
            Integer reviewerOrder = pp.getReviewerOrder();

            //通过审核，当前审核人换到上一层级
            LambdaQueryWrapper<PaymentRequestProcess> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PaymentRequestProcess::getPaymentRequestId,paymentRequestId)
                        .gt(PaymentRequestProcess::getReviewerOrder,reviewerOrder)
                        .orderByAsc(PaymentRequestProcess::getReviewerOrder)
                        .last("LIMIT 1");
            PaymentRequestProcess nextProcess = paymentRequestProcessMapper.selectOne(queryWrapper);
            PaymentRequest pr = paymentRequestMapper.selectById(paymentRequestId);
            String paymentType = pr.getPaymentType();//申请方式（0预付款，1应付款，2仅退款，3退货退款，4换货）
            if(nextProcess != null){
                reviewerUserId = nextProcess.getReviewerId();
            }else{

            }

            //当前审核人为财务主管时，生成出库单
            LambdaQueryWrapper<SysUserRole> query = new LambdaQueryWrapper<>();
            query.eq(SysUserRole::getUserId, reviewerId);
            SysUserRole sur = sysUserRoleMapper.selectOne(query);
            if(null == sur){
                throw new ServiceException(user.getNickName()+"未设置角色，请联系人事匹配后再操作。");
            }
            Long roleId = sur.getRoleId();
            SysRole sysRole = sysRoleMapper.selectRoleById(roleId);
            if(null == sysRole){
                throw new ServiceException(user.getNickName()+"未设置角色，请联系人事匹配后再操作。");
            }
            String roleName=  sysRole.getRoleName();
            if(roleName.equals("财务部主管")){
                if(paymentType != null && (paymentType.equals("2") || paymentType.equals("3") || paymentType.equals("4"))){
                    LambdaUpdateWrapper<PaymentRequest> lambdaUpdate = new LambdaUpdateWrapper<>();
                    lambdaUpdate.eq(PaymentRequest::getPaymentRequestId, paymentRequestId)
                            .set(PaymentRequest::getPaymentStatus, "7");//0未付款，1已生成付款单，2未过账，3已过账，4退款中，5退货退款中，6换货中，7已生成退款单
                    //更新为【已生成退款单】
                    paymentRequestMapper.update(null, lambdaUpdate);
                }

                //退货退款审核通过，生成出库单
                if(paymentType != null && (paymentType.equals("3") || paymentType.equals("4"))){
                    walmartStockPlanApi.saveWalmartStockPlanToPaymentReturn(paymentRequestProcess.getItems(), paymentType);
                }
            }
        }

        if(processStatus.equals("2")){
            LambdaQueryWrapper<PaymentRequest> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(PaymentRequest::getPaymentRequestId, paymentRequestId);
            PaymentRequest paymentRequest = paymentRequestMapper.selectOne(lambdaQueryWrapper);
            if(paymentRequest !=null && paymentRequest.getPaymentType().equals("3")||paymentRequest.getPaymentType().equals("4")){
                //审核拒绝，释放商品的锁定量
                unLockReservedQuantity(paymentRequestProcess.getPaymentRequestId());
            }

            //修改退款详情商品状态
            updatePaymentReturnStatus(paymentRequestProcess.getPaymentRequestId());

            LambdaUpdateWrapper<PaymentRequest> lambdaUpdate = new LambdaUpdateWrapper<>();
            lambdaUpdate.eq(PaymentRequest::getPaymentRequestId, paymentRequestId)
                    .set(PaymentRequest::getSolveStatus, "0")
                    .set(PaymentRequest::getPaymentStatus, "8");//0未付款，1已生成付款单，2未过账，3已过账，4退款中，5退货退款中，6换货中，7已生成退款单，8已驳回
            //更新为【已生成退款单】
            paymentRequestMapper.update(null, lambdaUpdate);


        }

        PaymentRequest pr = paymentRequestMapper.selectById(paymentRequestId);
        String procuredOrderId = pr.getProcuredOrderId();

        int rows = paymentRequestMapper.updatePaymentReviewStatus(paymentRequestId, newStatus, user.getNickName(), reviewerUserId);

        String paymentType = pr.getPaymentType();
        //申请方式（0预付款，1应付款，2仅退款，3退货退款，4换货）
        if(!paymentType.equals("0") && !paymentType.equals("1")){
            //更新采购订单状态：订单状态：0正常，1已完结，2仅退款中，3退货退款中，4换货中，5仅退款已驳回，6退货退款已驳回，7换货已驳回，8未完结
            procuredOrdersStatusAPi.setProcuredOrderStatus(Long.valueOf(procuredOrderId));

            if (paymentType.equals("2") || paymentType.equals("3")) {
                Integer reviewerOrder = getCurrentReviewerOrder(paymentRequestId, reviewerId);
                // 再次处理退款相关逻辑
                PaymentRequest p = paymentRequestMapper.selectById(paymentRequestId);
                processNextReviewerAndHandleReturn(paymentRequestId, reviewerOrder, p);
            }

        }

        return rows;
    }

    /**
     * 获取当前审核流程的审核顺序
     * @param paymentRequestId 付款申请ID
     * @param reviewerId 审核人ID
     * @return 审核顺序
     */
    private Integer getCurrentReviewerOrder(String paymentRequestId, Long reviewerId) {
        LambdaQueryWrapper<PaymentRequestProcess> qw = new LambdaQueryWrapper<>();
        qw.eq(PaymentRequestProcess::getPaymentRequestId, paymentRequestId);
        qw.eq(PaymentRequestProcess::getReviewerId, reviewerId);
        PaymentRequestProcess pp = paymentRequestProcessMapper.selectOne(qw);
        if (pp == null) {
            throw new ServiceException("获取审核流程明细失败。");
        }
        return pp.getReviewerOrder();
    }

    /**
     * 处理审核流程并返回下一个审核人ID
     * @param paymentRequestId 付款申请ID
     * @param reviewerOrder 当前审核人顺序
     * @param paymentRequest 付款申请对象
     * @return 下一个审核人ID
     */
    private Long processNextReviewerAndHandleReturn(String paymentRequestId, Integer reviewerOrder, PaymentRequest paymentRequest) {
        String paymentType = paymentRequest.getPaymentType();
        Long reviewerUserId = paymentRequest.getReviewerUserId();

        // 通过审核，当前审核人换到下一层级
        LambdaQueryWrapper<PaymentRequestProcess> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentRequestProcess::getPaymentRequestId, paymentRequestId)
                .gt(PaymentRequestProcess::getReviewerOrder, reviewerOrder)
                .orderByAsc(PaymentRequestProcess::getReviewerOrder)
                .last("LIMIT 1");
        PaymentRequestProcess nextProcess = paymentRequestProcessMapper.selectOne(queryWrapper);

        if (nextProcess != null) {
            reviewerUserId = nextProcess.getReviewerId();
        } else {
            if (paymentType.equals("2") || paymentType.equals("3")) {
                // 查询本次申请的明细
                List<PaymentReturn> returnDetailList = paymentReturnMapper.selectList(new LambdaQueryWrapper<PaymentReturn>()
                        .eq(PaymentReturn::getPaymentRequestId, paymentRequestId)
                        .eq(PaymentReturn::getDeleteStatus, Constants.NOT_DELETED_STATUS));

                // 遍历退款明细并格式化输出
                returnDetailList.forEach(returnItem -> {
                    StringBuilder operationLog = new StringBuilder();

                    // 根据付款类型添加对应的操作描述
                    if ("2".equals(paymentType)) {
                        operationLog.append("操作仅退款:\n");
                    } else {
                        operationLog.append("操作退货退款:\n");
                    }
                    String formattedDetail = String.format("SKU: %s | 数量: %s | 金额: %s\n",
                            returnItem.getSku() != null ? returnItem.getSku() : "未知",
                            returnItem.getQuantity() != null ? returnItem.getQuantity() : 0,
                            returnItem.getAmount() != null ? returnItem.getAmount() : BigDecimal.ZERO);
                    operationLog.append(formattedDetail);
                    ordersProductApi.updateLog(operationLog.toString(), returnItem.getProductId(), returnItem.getProcuredOderId());
                });

                // 汇总当前审核完订单中的产品退货或者退款是否全部退完
                List<PaymentRequest> list = paymentRequestMapper.selectList(
                        new LambdaQueryWrapper<PaymentRequest>()
                                .eq(PaymentRequest::getPaymentReviewStatus, Constants.PAYMENT_REVIEW_STATUS_APPROVED)
                                .in(PaymentRequest::getPaymentType, Arrays.asList("2", "3"))
                                .eq(PaymentRequest::getProcuredOrderId, paymentRequest.getProcuredOrderId())
                                .eq(PaymentRequest::getDeleteStatus, Constants.NOT_DELETED_STATUS)
                );

                // 提取申请款id查询申请退款明细
                List<PaymentReturn> paymentReturns = paymentReturnMapper.selectList(
                        new LambdaQueryWrapper<PaymentReturn>()
                                .in(PaymentReturn::getPaymentRequestId, list.stream().map(PaymentRequest::getPaymentRequestId).collect(Collectors.toList()))
                                .eq(PaymentReturn::getDeleteStatus, Constants.NOT_DELETED_STATUS)
                );

                // 根据订单id和productId进行分组，汇总申请数量
                Map<String, Integer> quantityMap = paymentReturns.stream()
                        .collect(Collectors.groupingBy(
                                p -> p.getProcuredOderId() + "-" + p.getProductId(),
                                Collectors.summingInt(PaymentReturn::getQuantity)
                        ));

                // 查询当前申请订单的所有产品数量
                List<OrdersProductDTO> ordersProductDTOS = ordersProductApi.selectByOrdersId(Integer.valueOf(paymentRequest.getProcuredOrderId()));
                ordersProductDTOS.forEach(item -> {
                    // 检查是否已经全部退货完毕了
                    Integer integer = quantityMap.get(item.getOrdersId() + "-" + item.getProductId());
                    Integer transferableNumber = item.getTransferableNumber();
                    if (Objects.equals(integer, transferableNumber)) {
                        if (paymentType.equals("2")) {
                            // 更新样式
                            int update = ordersProductApi.update(item.getId());
                            procuredOrdersStatusAPi.updateCancelStyleClass(paymentRequest.getProcuredOrderId()); // 更新样式并将采购订单状态设置为已完结
                        }
                        // 如果汇总的已退货数量和采购数量相等的话则更新订单产品的状态
                        ordersProductApi.updateReturnCompletedStatus(item.getId());
                        // 再查询采购订单信息
                        ProcuredOrders procuredOrders = procuredOrdersStatusAPi.selectById(paymentRequest.getProcuredOrderId());
                        // 根据采购计划id查询出所有的关联采购订单然后查询所有申请记录再根据productId进行分组
                        Map<String, Integer> integerMap = selectPaymentReturnMap(procuredOrders.getPlanId());
                        // 再根据采购计划id和productId查询到对应的采购产品
                        ProcuredProductDto dto = procuredProductApi.selectByPlanIdAndProductId(procuredOrders.getPlanId(), item.getProductId());
                        if (Objects.equals(dto.getNumber(), integerMap.get(item.getProductId().toString()))) {
                            // 要是采购计划产品对应数量也等于汇总的退货数量，则需要更新状态
                            procuredProductApi.updateReturnCompletedStatus(dto.getId());
                        }
                        // 查询到对应的销售计划将对应产品结束状态设置为未结束
                        salePlanApi.updateSelectStatus(procuredOrders.getPlanId(), item.getProductId());
                    }
                });
                // 查询采购订单中的产品是否已经全部仅退款完毕或者退货退款完，如果是，则更新订单状态为已结束
                List<OrdersProductDTO> ordersProduct = ordersProductApi.selectByOrdersId(Integer.valueOf(paymentRequest.getProcuredOrderId()));
                boolean result = ordersProduct.stream().allMatch(item -> item.getReturnCompletedStatus() == 1);
                if(result){
                    // 如果全部退款完或者退货完了则直接订单状态设置为已结束
                    procuredOrdersStatusAPi.updateStatus(paymentRequest.getProcuredOrderId());
                }

            }
        }

        return reviewerUserId;
    }

    private Map<String, Integer> selectPaymentReturnMap(Long planId) {
        // 在查询出所有的当前采购计划下的采购订单
        List<Long> orderIds = procuredOrdersStatusAPi.selectList(planId);
        // 查询出这些订单的所有申请记录进行汇总分组
        // 汇总当前审核完订单中的产品退货或者退款是否全部退完
        List<PaymentRequest> requestList = paymentRequestMapper.selectList(
                new LambdaQueryWrapper<PaymentRequest>()
                        .eq(PaymentRequest::getPaymentReviewStatus, Constants.PAYMENT_REVIEW_STATUS_APPROVED)
                        .in(PaymentRequest::getPaymentType, Arrays.asList("2", "3"))
                        .in(PaymentRequest::getProcuredOrderId, orderIds)
                        .eq(PaymentRequest::getDeleteStatus, Constants.NOT_DELETED_STATUS)
        );
        // 提取申请款id查询申请退款明细
        List<PaymentReturn> paymentReturnList = paymentReturnMapper.selectList(
                new LambdaQueryWrapper<PaymentReturn>()
                        .in(PaymentReturn::getPaymentRequestId, requestList.stream().map(PaymentRequest::getPaymentRequestId).collect(Collectors.toList()))
                        .eq(PaymentReturn::getDeleteStatus, Constants.NOT_DELETED_STATUS)
        );

        // 根据订单id和productId进行分组，汇总申请数量
        return paymentReturnList.stream()
                .collect(Collectors.groupingBy(
                        PaymentReturn::getProductId,
                        Collectors.summingInt(PaymentReturn::getQuantity)
                ));
    }

    /**
     * 审核拒绝，修改退款详情商品状态
     * @return
     */
    private void updatePaymentReturnStatus(String paymentRequestId) {

        LambdaUpdateWrapper<PaymentReturn> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PaymentReturn::getPaymentRequestId, paymentRequestId)
                .set(PaymentReturn::getDeleteStatus, "1");

        paymentReturnService.update(updateWrapper);
    }

    /**
     * 审核拒绝，释放商品的锁定量
     * @return
     */
    @Transactional
    public void unLockReservedQuantity(String paymentRequestId) {

        LambdaQueryWrapper<PaymentReturn> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PaymentReturn::getPaymentRequestId, paymentRequestId);

        List<PaymentReturn> items = paymentReturnMapper.selectList(queryWrapper);
        String procuredOrderId = items.isEmpty() ? "" : items.get(0).getProcuredOderId();
        items.forEach(item -> {
            item.setQuantity(0);
        });

        paymentRequestService.lockReservedQuantity( items, Long.valueOf(procuredOrderId));

    }

    /**
     * 更新申请表状态
     * @param paymentRequest
     * @return
     */
    @Override
    public int updatePaymentReviewStatusToPaymentVoucher(PaymentRequest paymentRequest) {

        String paymentRequestId = paymentRequest.getPaymentRequestId();
        String nickName = paymentRequest.getUpdateBy();
        String paymentReviewStatus = paymentRequest.getPaymentReviewStatus();
        String rejectRemark = paymentRequest.getPrepaymentRemark();

        //更新日志
        savePaymentRequestLog(paymentRequestId,paymentReviewStatus,nickName,rejectRemark);

        //更新主表状态
        Long reviewerUserId = paymentRequestMapper.selectById(paymentRequestId).getReviewerUserId();
        int row = paymentRequestMapper.updatePaymentReviewStatus(paymentRequestId, paymentReviewStatus, nickName, reviewerUserId);

        return row;
    }
    /**
     * 申请表日志
     * @return
     */
    public void savePaymentRequestLog(String paymentRequestId, String logStatus, String nickName, String logRemark){
        PaymentRequestLog log = new PaymentRequestLog(IdUtils.fastSimpleUUID(),paymentRequestId,
                logStatus,nickName,logRemark,DateUtils.getNowDate());
        paymentRequestLogMapper.insert(log);
    }
}
